import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import router from "@/router/index";

const API = axios.create({
  baseURL: "https://www.whalenav.cn",
  timeout: 10000,
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
});
// 请求拦截
API.interceptors.request.use((config) => {
  config.headers = config.headers || {};
  if (localStorage.getItem("company_token")) {
    config.headers.token = localStorage.getItem("company_token") || "";
  }
  return config;
});
// 响应拦截
let isEndToken = false;
API.interceptors.response.use(
  (respose) => {
    if (respose.data.code == 0) {
      ElMessage({
        type: "error",
        message: respose.data.msg,
      });
      return respose;
    } else if (respose.data.code == 1) {
      return respose;
    } else if (respose.data.code == 2) {
      if (!isEndToken) {
        isEndToken = true;
        ElMessageBox.confirm(`账号已过期，请重新登录?`, "操作提示", {
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            router.push("/login");
            isEndToken = false;
          })
          .catch((err) => {
            isEndToken = false;
          });
      }
    }
  },
  (err) => {
    return Promise.reject(err);
  }
);
export default API;
